const express = require('express')

const db = require('../db')
//引入密码加密 md5
const md5=require('md5-node')


//引入token
const jwt = require('jsonwebtoken')

const router =express.Router();


// --------------------------------------注册------------------------------------------

router.post('/register',(req,res)=>{
    let {phone,password}=req.body;
    password=md5(password)
    db(`select * from user where phone = '${phone}'`,(err,data)=>{
        if (err) {
            throw err;
        }
        //判断是否已经存在此用户
        if(data.length!==0){
            //存在:提示该用户已经注册
            res.send({
                code:0,
                msg:'该用户已经注册！'
            })
        }else{
            //不存在，添加该用户
            db(`insert into user(phone,password) values ('${phone}','${password}')`,(err,data)=>{
                if (err) {
                  throw err
                }
                res.send({
                    code:1,
                    msg:'注册成功！'
                })
              })
        }
    })
  })

// --------------------------------------登录------------------------------------------

router.post('/login',(req,res)=>{
    console.log(req.body);
    let {phone,password}=req.body;
    password=md5(password)
    db(`select user_id from user where phone = '${phone}' && password = '${password}'`,(err,data)=>{
        console.log(`select user_id from user where phone = '${phone}' && password = '${password}'`);
        // console.log(data);
        if (err) throw err;
        if (data.length) {
            let token ='Bearer ' +jwt.sign({user_id:data[0].user_id}, 'token', {expiresIn:'1day'});
            res.send({
                code:1,
                msg:'登录成功！',
                token
            })
        }else{
            // console.log(password);
            res.send({
                code:0,
                msg:'账号或者密码错误！'
            })
        }
    })
})







module.exports=router